<style lang="scss">
	@import "../utils/base.scss";

    .css1{
        text-align: center;

        height: 500px;
    }
    .vertical-center-modal{
        display: flex;
        align-items: center;
        justify-content: center;

        .ivu-modal{
            top: 0;
        }
    }
    .button_1{
        height: auto;
        font-size:13px;
        word-wrap: break-word !important;
        word-break: break-all !important;
        white-space: normal !important;
    }

</style>


<template>
	<div style="height:calc(100vh - 94px);background-color:#FFFFFF;overflow-y:auto;">
		<!-- <div class="qheader"> -->
		<div>
			<div class="qheader" slot="left">公告配置</div>
			<!-- <div slot="right" class="qheader" style="float:right;margin-right: 25px;">
                <Button type="primary" size="small" style="width: 80px;height: 25px;z-index:999"  @click="savenNotice()">保存</Button>
            </div> -->
		</div>
		<div class="gcontent">
			<Form name="activityinfo" :label-width="140" label-position="left" class="form form_left input">
				<Row>
					<Col span="8">
					<FormItem label="配置公告项:">
						<Select v-model="checkType" :transfer='true' style="z-index:999" @on-change="searchType">
							<Option v-for="item in processList" :value="item.serviceType" :key="item.serviceType">{{item.depname}}</Option>
						</Select>
					</FormItem>
					</Col>
					<Col span="16" style="text-align: end;">
					<Button type="primary" size="small" style="width: 80px;height: 25px;z-index:999" @click="savenNotice()">保存</Button>
					</Col>
				</Row>
				<Row v-show="showmd">
					<Col span="24">
					<mavon-editor ref="md" :toolbars='toolbars' :xssOptions="xssList"  v-model='mdvalue' style="height: 400px;z-index:100" @imgAdd="imgAdd"
					 @imgDel="imgDel"></mavon-editor>
					</Col>
				</Row>
			</Form>
		</div>

		<!-- 附件 -->
		<template>
			<div class="qheader" :style="{borderBottom: ishidden ? '' : '1px solid rgb(210,210,210)',}">
				<p>附件</p>
			</div>
			<component ref="file" :is="'file'" :ifedit="isedit" :files="file"></component>
		</template>

	</div>
</template>


<script>
	import ajax from "../ajax_util"
	var mavonEditor = require('mavon-editor')
	import 'mavon-editor/dist/css/index.css'
	import file from '../base/notice_file'
	import Axios from 'axios'
	var xss = require('xss');

	var md_img_g = {}

	export default {
		name: 'editor',
		components: {
			'mavon-editor': mavonEditor.mavonEditor,
			file
		},

		data() {
			return {
				xssList: {
					  whiteList: xss.whiteList
					},
				toolbars: {
					bold: true, // 粗体
					italic: true, // 斜体
					header: true, // 标题
					underline: true, // 下划线
					strikethrough: true, // 中划线
					mark: true, // 标记
					superscript: true, // 上角标
					subscript: true, // 下角标
					quote: true, // 引用
					ol: true, // 有序列表
					ul: true, // 无序列表
					link: true, // 链接
					imagelink: true, // 图片链接
					code: true, // code
					table: true, // 表格
					fullscreen: true, // 全屏编辑
					readmodel: true, // 沉浸式阅读
					htmlcode: true, // 展示html源码
					help: true, // 帮助
					/* 1.3.5 */
					undo: true, // 上一步
					redo: true, // 下一步
					trash: true, // 清空
					save: false, // 保存（触发events中的save事件）
					/* 1.4.2 */
					navigation: true, // 导航目录
					/* 2.1.8 */
					alignleft: true, // 左对齐
					aligncenter: true, // 居中
					alignright: true, // 右对齐
					/* 2.2.1 */
					subfield: true, // 单双栏模式
					preview: true, // 预览
				},
				showmd: true,
				processList: [],
				checkType: "",
				mdvalue: '',
				fileUrl: this.CONFIG.file_url,
				img_file: {},
				file: [],
				ishidden: false,
				isedit: false,
				filesList: []
			}
		},
		mounted: function() {
			this.getAllProcess()

		},

		methods: {
			getAllProcess() {
				var url = this.CONFIG.base_url_test + "/acti-services"
				var that = this;
				ajax.get({
					url: url,
					that: that,
					params: null,
					success: function(data) {
						console.log('1', data)
						that.processList = data
						that.checkType = data[0].serviceType
						that.searchType()
					}
				})
			},
			searchType(type) {
				console.log('ct', this.checkType)
				console.log('type', type)
				//console.log('pl',this.processList)
				//this.setmdvalue()
				this.setmdvalue()
				this.showmd = true

			},
			// setmdvalue(){
			//     var url = this.CONFIG.base_url_test + '/notice/' + this.checkType
			//     var that=this;
			//     ajax.get({
			//         url:url,
			//         that:that,
			//         success:function(data){
			//             console.log('data',data)
			//             if(data != undefined && data.length > 0){

			//                 var matched_arr =  data[data.length-1].noticeContent.match(/\!\[.*?]\((.*?)\)/g);
			//                 var img_name = []
			//                 for(var i in matched_arr){
			//                     img_name[i] = /\!\[.*?]\((.*?)\)/g.exec(matched_arr[i])[1];
			//                 }
			//                 console.log('img_name',img_name)

			//                 that.setfile(img_name)

			//                 that.mdvalue = data[data.length-1].noticeContent
			//                 that.file = data[data.length-1].files
			//             }else if(that.mdvalue != ''){
			//                 that.mdvalue = ''
			//             }
			//         }
			//     })
			// },

			// setfile(img_file){
			//     console.log('img_file',img_file.length)
			//     if (img_file.length > 0) {
			//         for (let index = 0; index < img_file.length; index++) {
			//             var url = this.fileUrl + '/file/' + img_file[index]
			//             var that=this
			//             Axios.get(url,{responseType: 'blob'
			//             }).then(function(response){
			//                 var blob = new Blob([response.data])
			//                 var href = window.URL.createObjectURL(blob)

			//                 that.$refs.md.$imgUpdateByUrl(img_file[index], href)
			//                 return href
			//             })
			//         }
			//     }
			// },

			// $imgAdd(pos, $file){
			//     var formdata = new FormData();
			//     formdata.append('file', $file);
			//     console.log('formdata',formdata)
			//     Axios({
			//         url: this.fileUrl + '/file',
			//         method: 'post',
			//         data: formdata,
			//         headers: { 'Content-Type': 'multipart/form-data' },
			//     }).then((url) => {

			//         console.log('pos_url',url)
			//         this.$refs.md.$img2Url(pos, url.data)
			//         this.$refs.md.$imgUpdateByUrl(url.data, $file.miniurl);
			//     })
			// },

			// saveMavon(){
			//     var url = this.CONFIG.base_url_test + '/notice'
			//     var that=this;
			//     let temp = {
			//         files:that.file,
			//         noticeContent:that.mdvalue,
			//         processKey:that.checkType,
			//     }
			//     ajax.post({
			//         url:url,
			//         that:that,
			//         data:temp,
			//         success:function(data){
			//             console.log('data:',data)
			//             that.$Message.success('提交成功!');
			//         }
			//     })
			// },

			// 分割线
			imgAdd(filename, imgfile) {
				let img_name = guid(this.$store.state.user.id);
				this.$refs.md.$img2Url(filename, img_name); //md中图片改名
				this.$refs.md.$imgUpdateByUrl(img_name, imgfile.miniurl); //md中图片改名后会对应不上图片文件，这里是把图片文件重新给对应图片
				md_img_g[img_name] = imgfile; //记录图片，后面上传用
			},
			imgDel(filename) {
				console.log('------------imgDel------------', filename)
			},

			setmdvalue() {
				var url = this.CONFIG.base_url_test + '/notice/' + this.checkType
				var that = this;
				ajax.get({
					url: url,
					that: that,
					success: function(data) {
						console.log('data', data)
						that.file = []
						that.mdvalue = ''
						if (data != undefined && data.length > 0) {

							var matched_arr = data[data.length - 1].noticeContent.match(/\!\[.*?]\((.*?)\)/g);
							var img_names = []
							for (var i in matched_arr) {
								img_names.push(/\!\[.*?]\((.*?)\)/g.exec(matched_arr[i])[1])
							}

							that.$nextTick(() => {
								that.setfile(img_names)
							})

							that.mdvalue = data[data.length - 1].noticeContent
							that.file = data[data.length - 1].files
						}
					}
				})

			},

			setfile(img_file) {
				console.log('img_file', img_file.length)
				var that = this
				if (img_file.length > 0) {
					for (let index = 0; index < img_file.length; index++) {
						var url = that.fileUrl + "/image/" + img_file[index] + ".png";
						Axios.get(url, {
							responseType: 'blob'
						}).then(function(response) {
							var blob = new Blob([response.data])
							var href = window.URL.createObjectURL(blob)
							console.log('href', href)
							that.$refs.md.$imgUpdateByUrl(img_file[index], href)
							return href
						})
					}
				}
			},
			change (value, render) {
				// render 为 markdown 解析后的结果(转化成了HTML格式）
				var t = xss(value)
				console.log(value, "------------>>", t)
				value = t
				this.mdvalue = ""
			},

			savenNotice() {
				var that = this;
				var formdata = new FormData();
				var img_arr = []
				var matched_arr = that.mdvalue.match(/\!\[.*?]\((.*?)\)/g);
				console.log("v", md_img_g, that.mdvalue)
				for (var i in matched_arr) {
					console.log("for")
					var img_name = /\!\[.*?]\((.*?)\)/g.exec(matched_arr[i])[1];
					img_arr.push({
						name: img_name
					})
					formdata.append(img_name, md_img_g[img_name])
				}

				var img_url = this.fileUrl + '/named-images'
				console.log('img_url', img_url)
				console.log('formdata', formdata)
				// console.log('that.$refs.file.files:',that.$refs.file.files)
				let temp = {
					files: that.file,
					noticeContent: that.mdvalue,
					processKey: that.checkType,
				}
				Axios({
					url: img_url,
					method: 'post',
					data: formdata,
					headers: {
						'Content-Type': 'multipart/form-data'
					},
				}).then(response => {
					ajax.post({
						url: that.CONFIG.base_url_test + '/notice',
						that: that,
						data: temp,
						success: function(data) {
							console.log('data:', data)
							that.$Message.success('提交成功!');
						}
					})
				})
			},

		}
	}

	function guid(userId) {
		var time = new Date().getTime()
		var use = '' + userId
		var user = use
		for (let i = 0; i < 5 - use.length; i++) {
			user += '0'
		}
		var temp = parseInt(time + '' + user).toString(32) + '' + parseInt(Math.random() * 100000)
		console.log(time, user, parseInt(time + '' + user), temp)

		return temp;
	}
</script>
